//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.TridentComposer
{
    using System;
    using Microsoft.Research.ScientificWorkflow.TridentModel;
    using SR = Microsoft.Research.eResearch;
    using System.IO;

    public class SaveToFilesystemProxy : MarshalByRefObject
    {
        #region Private fields
        private string targetFileName;
        private TridentWorkflowModel workflowToSave;
        private SR.Connection registryConnection;
        private string tempDir; 
        #endregion

        /// <summary>
        /// Dummy constructor to allow creation of object through CreateInstanceAndUnwrap API.
        /// </summary>
        public SaveToFilesystemProxy()
        {
        }

        /// <summary>
        /// Initializes a new instance of the proxy.
        /// </summary>
        /// <param name="targetFileName">The filename of the xoml.</param>
        /// <param name="workflow">The workflow to be saved.</param>
        /// <param name="connection">The connnection.</param>
        public SaveToFilesystemProxy(string targetFileName, TridentWorkflowModel workflow, SR.Connection connection)
        {
            #region Argument Validation
            if (string.IsNullOrEmpty(targetFileName))
            {
                throw new ArgumentNullException("targetFileName");
            }
            if (workflow == null)
            {
                throw new ArgumentNullException("workflow");
            }
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            #endregion

            tempDir = WorkflowComposer.CreateTempDirectory();
            this.Init(targetFileName, tempDir, workflow, connection);
        }

        /// <summary>
        /// Create a new appdomain and save the workflow to file system.
        /// </summary>
        public void Execute()
        {
            AppDomain childAppdomain = null;
            try
            {
                childAppdomain = this.CreateAppDomain();
                
                SaveToFilesystemProxy proxyObject = childAppdomain.CreateInstanceAndUnwrap("Microsoft.Research.ScientificWorkflow.TridentComposer", "Microsoft.Research.ScientificWorkflow.TridentComposer.SaveToFilesystemProxy") as SaveToFilesystemProxy;
                proxyObject.Init(this.targetFileName, this.tempDir, this.workflowToSave, this.registryConnection);
                proxyObject.SaveWorkflow();
            }
            finally
            {
                UnloadAppDomain(childAppdomain);
                Directory.Delete(this.tempDir, true);
            }
        }

        /// <summary>
        /// Save workflow to filesystem.
        /// </summary>
        private void SaveWorkflow()
        {
            ActivityComposer activityComposer = new ActivityComposer(this.registryConnection, false);
            WorkflowComposer composer = new WorkflowComposer(this.registryConnection, activityComposer);
            
            composer.SaveWorkflow(this.workflowToSave, targetFileName, tempDir);
        }

        /// <summary>
        /// Initialize the proxy.
        /// </summary>
        /// <param name="targetFileName">The file name.</param>
        /// <param name="tempDir">The temp directory to download files to.</param>
        /// <param name="workflow">The workflow to save.</param>
        /// <param name="connection">The connection object.</param>
        private void Init(string targetFileName,string tempDir, TridentWorkflowModel workflow, SR.Connection connection)
        {
            this.targetFileName = targetFileName;
            this.tempDir = tempDir;
            this.workflowToSave = workflow;
            this.registryConnection = connection;
            SR.SR_Connection.Init();
            this.registryConnection.Open();
        }

        /// <summary>
        /// Creates a new app domain.
        /// </summary>
        /// <returns>New instance of the app domain.</returns>
        private AppDomain CreateAppDomain()
        {
            AppDomain newDomain = AppDomain.CreateDomain("SaveToFileSystemAppDomain");
            newDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
            return newDomain;
        }

        /// <summary>
        /// Unloads the executor app domain.
        /// </summary>
        /// <param name="executorDomain">Instance of the AppDomain.</param>
        private static void UnloadAppDomain(AppDomain appDomain)
        {
            if (appDomain != null)
            {
                AppDomain.Unload(appDomain);
            }
        }

        /// <summary>
        /// Method logs the unhandled exception in the app domain.
        /// </summary>
        /// <param name="sender">Object who raises the unhandled exception.</param>
        /// <param name="e">Event argument containing exception details.</param>
        private void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // TODO : Log.
        }
    }
}
